package com.exam.entity.dto;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.jpa.domain.Specification;

import com.achievement.entity.Course;
import com.exam.entity.Exam;

public class ExamDTO {
	public static Specification<Exam> getSpecification(List<Long> course_ids,String str,Long course_id) {
		Specification<Exam> spec = new Specification<Exam>() {
			public Predicate toPredicate(Root<Exam> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

				List<Predicate> result_list = new ArrayList<Predicate>();
				
				Predicate[] p = new Predicate[result_list.size()];
				if(null!=course_ids&&course_id==null) {
					List<Predicate> list = new ArrayList<Predicate>();
					for(Long id:course_ids) {
						Join<Exam,Course> join = root.join(root.getModel().getSingularAttribute("course",Course.class),JoinType.LEFT);
						Predicate  predicate =  cb.equal(join.get("id").as(Long.class),id);
						list.add(predicate);
					}
					Predicate  result =  cb.or(list.toArray(p));
					result_list.add(result);
				}
				if(!"".equals(str)&&str!=null) {
					List<Predicate> list = new ArrayList<Predicate>();
					Predicate  predicate1 =  cb.like(root.get("name").as(String.class),"%"+str+"%");
					list.add(predicate1);
					Predicate  predicate2 =  cb.like(root.get("num").as(String.class),"%"+str+"%");
					list.add(predicate2);

					Predicate  result =  cb.or(list.toArray(p));
					result_list.add(result);
				}
				if(course_id!=null) {
					Join<Exam, Course> join = root.join(root.getModel().getSingularAttribute("course",Course.class),JoinType.LEFT);
					Predicate  predicate =  cb.equal(join.get("id").as(Long.class),course_id);
					result_list.add(predicate);
				}
				return cb.and(result_list.toArray(p));
			}
		};
		return spec;
	}
}
